package org.chaiyi.template.core.register.contractor.bean;

import lombok.extern.slf4j.Slf4j;
import org.chaiyi.template.core.common.contract.ContractInfo;
import org.chaiyi.template.core.common.contract.ContractUtil;
import org.chaiyi.template.core.common.contract.Contractor;
import org.chaiyi.template.core.common.util.ClassPathUtil;
import org.chaiyi.template.core.register.contractor.bean.process.ContractInfoRegister;
import org.chaiyi.template.core.register.contractor.bean.process.IServiceProcess;
import org.chaiyi.template.core.register.contractor.bean.process.MongoRepositoryRegister;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 通过ContractInfo可以注册bean都在这里注册了
 * 使用自己写的扫描方式，Spring提供的扫描方式可以参考SupporterCacheRegister
 *
 * @author Gong.Yang
 */
@Slf4j
@Order(-99)
@Component
public class ContractorRegister implements BeanDefinitionRegistryPostProcessor {
    private final List<IServiceProcess> processList = List.of(
            new ContractInfoRegister(),
            new MongoRepositoryRegister()
    );

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        List<Class<?>> classes = ClassPathUtil.scanPackage("org.chaiyi.template.contract",
                Contractor.class::isAssignableFrom);

        for (Class<?> iService : classes) {
            ContractInfo<?, ?> info = ContractUtil.getInfoByIService(iService);
            for (IServiceProcess process : processList) {
                process.register(info, registry);//具体的注册逻辑
            }
        }
        log.info("【Definition】IServiceRegister complete!");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
